import React from 'react'
import { Modal,Row,Col, message } from 'antd'
import service from '../../../service'
import Checkbox from 'antd/lib/checkbox/Checkbox'

export default function SetRole(props) {
  const [allRole,setAllRole]=React.useState([])
  const [user_role,setUser_role]=React.useState([])
  const [checkList,setCheckList]=React.useState([])
  React.useEffect(()=>{
    if(props.user_key===undefined){
      service.allRole().then((res)=>{
      setAllRole(res.data)
    })
    }
    service.user_role({data:props.user_key}).then((res)=>{
      setUser_role(res.data)
      setCheckList(res.data)
    })
  },[props.user_key])
  const checkChange = (e,role)=>{
    let checkbox = [...checkList]
    if(e.target.checked){
      checkbox.push(role)
    }else{
      checkbox=checkbox.filter((item)=>item.key!==role.key)
    }
    setCheckList(checkbox)
  }
  const ok = ()=>{
    if(checkList.length===1){
      let list =[]
      checkList.map((item)=>{
        list.push(item.key)
      })
      service.user_role_({user_key:props.user_key,role_key:list})
      service.user_role({data:props.user_key}).then((res)=>{
        setUser_role(res.data)
        setCheckList(res.data)
      })
      message.success('修改成功')
      props.close()
    }
    else{
      message.info('只能选择一种角色')
    }
  }
  return (
    <Modal
      title='设置用户角色'
      destroyOnClose
      okText='设置'
      cancelText='取消'
      onCancel={()=>{
        props.close()
      }}
      visible={props.visible}
      onOk = {ok}
    >
      <h3 style={{color:'#ff4d4f',marginBottom:'10px'}}>给用户：<span style={{color:'#000000'}}>{props.user_name}</span>设置角色</h3>
      <hr/>
      <Row style={{marginTop:'20px'}}>
        {
          allRole.map((role,index)=>{
            role.false=false
            if(user_role.length!==0){
                user_role.map((role1)=>{
                  if(role1.key===role.key){
                    role.false=true
                  }
                })
            }
            return <Col span={8} key={role.key}><Checkbox key={role.key} onChange={(e)=>{checkChange(e,role)}} defaultChecked={role.false}>{role.name}</Checkbox></Col>
          })
        }
      </Row>
    </Modal>
  )
}
